// @ts-nocheck
import { type Ref as VueRef} from 'vue';
import {h, onUnmounted, reactive, ref} from "vue";
import {axios_request} from "@/api/milliaAxios";
import {ElMessage, ElNotification} from "element-plus";
import {sleep} from "@/static/Login_Register/register";


// ==========================================================================

export const {
    percentage,
    countdownText,
    startCountdown,
    resetCountdown
} = useCountdown();



// ================================================================================
// 是否出现弹窗：使用镜像的名称作为key
export const isShowTopic = reactive({
    nginx: false,
    web_2016_unserialize: false,
    web_2015_filemanager: false,
    web_2018_unfinish: false,
})

export const isBegin = reactive({
    nginx: false,
    web_2016_unserialize: false,
    web_2015_filemanager: false,
    web_2018_unfinish: false,
})

// 存储题目IP地址
export const topic_ip = ref('')

// ==================================== 创建或销毁环境 ===============================

export const ctfForm = reactive({
    'title': '',
    'action': '',
})

export async function getTopic(topic_name: string, action: string) {
    ctfForm.title = topic_name;
    ctfForm.action = action;

    const res = await axios_request('/api/CTF/web_topic/', JSON.stringify(ctfForm), 'post')
    console.log("POST请求返回的数据：");
    console.log(res);

    if (res.status == 200) {
        if (ctfForm.action == 'start') {
            topic_ip.value = '172.17.0.1:' + res.data.port
            isBegin[topic_name] = true;
            startCountdown(topic_name)
        } else if (ctfForm.action == 'stop') {
            isBegin[topic_name] = false;
            resetCountdown()
        }

        ElNotification({
            title: 'Success',
            message: h('span', {style: {color: '#65e0c2', fontSize: '16px', fontWeight: '900'}}, res.data.msg),
            type: 'success',
            offset: 65,
            showClose: false,
            customClass: 'custom-notification'
        })

        // 重置数据
        ctfForm.title = '';
        ctfForm.action = '';
        // isShowTopic[topic_name] = false;
    } else {
        ElNotification({
            title: 'Error',
            message: h('span', {style: {color: '#65e0c2', fontSize: '16px', fontWeight: '900'}}, res.data.msg),
            type: 'error',
            offset: 65,
            showClose: false,
            customClass: 'custom-notification'
        })
    }
}

// =================================== 提交Flag ====================================

// 提交Flag的表单
export const flagForm = reactive({
    'flag': '',
    'title': ''
})

export async function submitFlag(topic_name: string) {
    flagForm.title = topic_name;

    const res = await axios_request('/api/CTF/check_web_flag/', JSON.stringify(flagForm), 'post')
    console.log("POST请求返回的数据：");
    console.log(res);

    if (res.status == 200) {
        ElNotification({
            title: 'Success',
            message: h('span', {style: {color: '#65e0c2', fontSize: '16px', fontWeight: '900'}}, res.data.msg),
            type: 'success',
            offset: 65,
            showClose: false,
            customClass: 'custom-notification'
        })

        await sleep(4000);
        window.location.reload();

    }else {
        ElMessage.warning(res.data.msg)
    }
}


// =================================== 显示进度并倒计时 ===============================
interface CountdownReturn {
    remainingTime: VueRef<number>;
    percentage: VueRef<number>;
    countdownText: VueRef<string>;
    startCountdown: () => void;
    resetCountdown: () => void;
}

function useCountdown(): CountdownReturn {
    const remainingTime = ref(1800); // 30 minutes in seconds
    const percentage = ref(100); // Start at 100%
    const countdownText = ref('30:00');

    let intervalId: ReturnType<typeof setInterval> | null = null;

    const startCountdown = (topic_name: string) => {
        intervalId = setInterval(() => {
            if (remainingTime.value > 0) {
                remainingTime.value -= 1;
                percentage.value = Math.round((remainingTime.value / 1800) * 100);
                const minutes = Math.floor(remainingTime.value / 60);
                const seconds = remainingTime.value % 60;
                countdownText.value = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
            } else {
                clearInterval(intervalId as ReturnType<typeof setInterval>);
                percentage.value = 0;
                countdownText.value = '00:00';
                // 销毁环境
                getTopic(topic_name, 'stop').then()
            }
        }, 1000);
    };

    const resetCountdown = () => {
        if (intervalId) {
            clearInterval(intervalId);
            intervalId = null;
        }
        remainingTime.value = 1800;
        percentage.value = 100;
        countdownText.value = '30:00';
    };

    onUnmounted(() => {
        if (intervalId) {
            clearInterval(intervalId);
        }
    });

    return { remainingTime, percentage, countdownText, startCountdown, resetCountdown };
}

// 进度条变色
export const customColorMethod = (percentage: number) => {
    if (percentage < 30) {
        return '#eb2c2c'
    }
    if (percentage < 70) {
        return '#e6a23c'
    }
    return 'rgb(1,154,133)'
}
